/*
 * Created by Christopher King
 * Copyright (C) 2007 Christopher King, All Rights Reserved.
 */

package us.cirion.adventure.ui.mobile;

import java.util.Vector;

import us.cirion.adventure.engine.Word;

/**
 * MainMenu is a simple screen that looks for all games that have been
 * installed, and presents a menu of them all to the user. It will launch any
 * selected game.
 * 
 * @author Chris
 */
class MainMenu implements InputListener
{

	private AdventureGameEngine engine;
	private HUDCanvas display;

	public MainMenu(AdventureGameEngine engine, HUDCanvas display)
	{
		this.engine = engine;
		this.display = display;
	}

	public void displayMenu()
	{
		display.setInputListener(this);
		display.setDirections(new Vector());
		Vector choices = buildChoices();
		String menuText = buildMenuText(choices);
		display.setRoomText(menuText);
		display.resetWords();
		display.addWords(choices);
		display.repaint();
	}

	private Vector buildChoices()
	{
		// Currently, we just scan through the JAD to see what's in there.
		// Version 2 will also support reading locally-stored files, as well
		// as browsing for more online.
		Vector games = new Vector();
		int gameIndex = 1;
		String dataPrefix = "IncludedGameData";
		String namePrefix = "IncludedGameName";
		String gameName = null;
		String gameData = null;
		do
		{
			String gameDataKey = dataPrefix + gameIndex;
			gameData = engine.getAppProperty(gameDataKey);
			String gameNameKey = namePrefix + gameIndex;
			gameName = engine.getAppProperty(gameNameKey);
			if (gameName != null && gameData != null)
			{
				NewGameWord word = new NewGameWord(gameIndex, gameData,
						gameName);
				games.addElement(word);
			}
			++gameIndex;
		} while (gameName != null && gameData != null);
		return games;
	}

	private String buildMenuText(Vector choices)
	{
		// TODO: Should probably extract this string from... where? UI config?
		// Maybe  we can just i18n it.
		StringBuffer textBuffer = new StringBuffer();
		textBuffer.append("You have opened the Adventure Game Treasure Chest!  Please choose a game to play.");
		for (int i = 0; i < choices.size(); ++i)
		{
			NewGameWord word = (NewGameWord) choices.elementAt(i);
			textBuffer.append('\n');
			textBuffer.append(word.getDisplayText());
			textBuffer.append(": ");
			textBuffer.append(word.getGameName());
		}
		return textBuffer.toString();
	}

	public void handleWord(Word word)
	{
		NewGameWord newGameWord = (NewGameWord) word;
		engine.newGame(newGameWord.getGameFile());
	}

}
